package com.youmu.sichuansfc.dao.impl;

import com.youmu.sichuansfc.dao.CompanyDao;
import com.youmu.sichuansfc.domain.YoumuCompany;
import com.youmu.sichuansfc.domain.pojo.AreaPojo;
import com.youmu.sichuansfc.domain.pojo.CompanyCountPojo;
import com.youmu.sichuansfc.dto.rsp.CompanyT;
import com.youmu.sichuansfc.enums.CompanyStatisticEnum;
import com.youmu.sichuansfc.util.CompanyDetailUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class CompanyDaoImpl implements CompanyDao {

    private EntityManager em;
    @PersistenceContext
    public void setEm(EntityManager em) {
        this.em = em;
    }
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public YoumuCompany insert(YoumuCompany youmuCompany) {
        if(youmuCompany.getId() != null){
//            if(youmuCompany.getIsDelete()){
//                youmuCompany = findById(youmuCompany.getId());
//                youmuCompany.setIsDelete(true);
//            }
            em.merge(youmuCompany);
        }else{
            em.persist(youmuCompany);
        }
        return youmuCompany;
    }

    @Override
    public CompanyT findBy(Timestamp startTime, Timestamp endTime, String companyName, Integer companyStatus, int num, int size) {

        Map<String,Object> params = new HashMap<>();
        StringBuffer sql = new StringBuffer();
        sql.append("from YoumuCompany where is_delete = 0 ");
        if(startTime != null ){
            sql.append(" and add_time >=:startTime");
            params.put("startTime",startTime);
        }
        if(endTime != null){
            sql.append(" and add_time <=:endTime");
            params.put("endTime",endTime);
        }
        if(StringUtils.isNotEmpty(companyName)){
            sql.append(" and company_name like:companyName");
            params.put("companyName","%"+companyName+"%");
        }
        if(companyStatus != null){
            sql.append(" and companyStatus =:companyStatus");
            params.put("companyStatus",companyStatus);
        }

        sql.append(" order by add_time DESC");

        Query query =  em.createQuery(sql.toString(), YoumuCompany.class);
        for(String key : params.keySet()){
            query.setParameter(key,params.get(key));
        }

        // 录入总共多少份档案
        CompanyT companyT = new CompanyT();
        companyT.setCompanyCount(query.getResultList().size());

        List<YoumuCompany> youmuCompanies = query
                .setFirstResult(num*size)
                .setMaxResults(size)
                .getResultList();
        companyT.setYoumuCompanyList(youmuCompanies);

        return companyT;
    }

    @Override
    public YoumuCompany findById(long id) {
        String hql = "from YoumuCompany where is_delete = 0 and id =:id ";
        List<YoumuCompany> youmuCompanys = em.createQuery(hql, YoumuCompany.class)
                .setParameter("id", id)
                .getResultList();
        YoumuCompany youmuCompany = null;
        if(youmuCompanys != null && youmuCompanys.size() > 0){
            youmuCompany = youmuCompanys.get(0);
            if(!StringUtils.isNotEmpty(youmuCompany.getDetail())){
                try {
                    youmuCompany.setDetail(CompanyDetailUtil.getCompanyDetail(youmuCompany.getCompanyName()));
                }catch (Exception e){
                    //e.printStackTrace();
                }
            }
        }
        return  youmuCompany;
    }

    @Override
    public List<YoumuCompany> findByCompanyType(int companyStatus) {
        String hql = "from YoumuCompany where is_delete = 0 and companyStatus =:companyStatus ";
        List<YoumuCompany> youmuCompanys = em.createQuery(hql, YoumuCompany.class)
                .setParameter("companyStatus", companyStatus)
                .getResultList();
        return  youmuCompanys;
    }

    @Override
    public int errorCompany() {
        String hql = "from YoumuCompany where is_delete = 0 and companyStatus in (2,3,4)";
        return em.createQuery(hql, YoumuCompany.class).getResultList().size();
    }


    @Override
    public List<CompanyCountPojo> findByType(Integer sqlKey, List<AreaPojo> areaPojos) {

        String hql = "select  *,  count(*)  from youmu_company where is_delete = 0 ";
        Map<String, Object> params = new HashMap<>();
        //拼接 地区IDs
        List<String> areaIds = new ArrayList<>();
        if (areaPojos != null && areaPojos.size() > 0){
            for (AreaPojo areaPojo : areaPojos){
               areaIds.add(areaPojo.getId().toString());
            }
        }
        if(areaIds != null && areaIds.size() > 0){
            logger.info(StringUtils.join(areaIds, ","));
            hql += " and area_id in ( "+StringUtils.join(areaIds, ",")+" ) ";
            // map.put("areaIds",StringUtils.join(areaIds, ",") );
        }
        // FIXME
        if (sqlKey != null) {
            hql += " group by " + CompanyStatisticEnum.CompanyStatistic.get(sqlKey + "").toString();
            logger.info(CompanyStatisticEnum.CompanyStatistic.get(sqlKey+"").toString());
        }
        logger.info(hql);
        Query query = em.createNativeQuery(hql, CompanyCountPojo.class);
        for(String key : params.keySet()){
            query.setParameter(key, params.get(key));
        }
        List<CompanyCountPojo> youmuCompanyList = query.getResultList();
        try {
             youmuCompanyList.get(0).getId();
             return youmuCompanyList;
        }catch (Exception e){

        }

        return null;
    }
}
